<template>
  <div class="tableBase">
    <div class="warning">
      <p>
        <i>◎</i>
        如果您对execl操作比较熟悉，可以下载后台订单，筛选后直接上传
      </p>
      <p>
        <i>◎</i>
        您也可以
        <a href="../../../../../static/files/求礼品导入模板(all).zip">
          <strong class="text-button-b">下载模板</strong>
        </a>
        按模板内容填写后上传
      </p>
      <!-- <p class="tipsErr">
        <i>◎</i>
        请尽量控制上传的文件SKU在8个以内!!!
      </p>
      <p class="tipsErr">
        <i>◎</i>
        若您不需要给客户发礼品, 请直接删除客户信息切勿隐藏!!!
      </p> -->
    </div>
    <div class="upload">
      <el-upload :accept="acceptArr" :show-file-list="false" action="" :http-request="requestUpload" :headers="headers">
        <b class="button-n" v-if="uploadStatus == 1">上传表格</b>
        <b class="button-w" v-if="uploadStatus == 2 || uploadStatus == 3">重新上传</b>
      </el-upload>
    </div>
    <p class="tips" v-if="uploadStatus==2">
      错误提示：请确认是否上传的是平台导出的原表格，有字段缺失或被修改导致无法识别
    </p>
    <div class="failDetail" v-if="uploadStatus==3">
      <p>
        总计
        <strong>{{ tables.totalNum }}</strong>
        位收货人，识别成功
        <strong>{{ tables.realNum }}</strong>
        条，失败
        <strong>{{ (tables.totalNum - tables.realNum) || '0' }}</strong>
        条
      </p>
      <b class="text-button-b" @click="downFail">下载失败列表</b>
    </div>
    <div class="elAlert">
      <el-dialog custom-class="errorTip" title="错误提示" :modal-append-to-body="false" :visible.sync="errorTipObj.show" width="440px" top="15vh">
        <p>您的表格中有客户id信息重复，请确认</p>
        <ul class="errorList">
          <li v-for="(item, index) in errorTipObj.arr" :key="index">{{ item }}</li>
        </ul>
        <div class="footer">
          <b class="button-w" @click="errorTipObj.show=false">有问题，返回修改</b>
          <b class="button-n" @click="goWhere('checkPackage')">没问题，直接发货</b>
        </div>
      </el-dialog>
      <loadingBase v-if="isUpload"></loadingBase>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters, mapActions } from 'vuex'
import { uploadFile, uploadPost } from '../../../../assets/js/upload.js'
import LoadingBase from '../../../base/loadingBase'
export default {
  name: 'tableBase',
  components: {
    LoadingBase
  },
  props: {
    shopType: {
      type: Number
    }
  },
  data () {
    return {
      uploadStatus: 1,
      isUpload: false,
      acceptArr: ['.csv', '.xlsx', '.xls'],
      errorTipObj: {
        show: false,
        arr: []
      },
      uploadFileName: ''
    }
  },
  computed: {
    headers () {
      return {
        accesstoken: this.userToken,
        userAccountId: this.userInfo.sellerAccountId
      }
    },
    ...mapGetters([
      'userInfo',
      'userToken',
      'tables'
    ])
  },
  methods: {
    goWhere (router) { // 跳转
      this.$router.push({ name: router })
    },
    downFail () { // 下载失败列表
      window.open(`/file/task/downloadErrorOrderIds?fileName=${this.tables.uploadFileName}&shopType=${this.tables.shopType}&filePostfix=${this.tables.filePostfix}`)
    },
    requestUpload (config) {
      let params = {
        file: config.file,
        oldFileName: config.file.name,
        shopType: this.shopType,
        sellerAccountId: this.userInfo.sellerAccountId
      }
      uploadFile(config, params).then((res) => {
        if (this.acceptArr.indexOf(res.filePostfix) < 0) {
          this.uploadStatus = 2
          this.$message({
            message: '请上传csv/xls/xlxs格式文件',
            type: 'error'
          })
        } else { // 文件格式通过
          this.$message({
            message: '文件上传中, 请稍等!!!',
            type: 'warning',
            duration: 0,
            showClose: true
          })
          this.isUpload = true
          this.uploadDetail(res)
        }
      }).catch((error) => {
        this.$message.closeAll()
        console.error(error)
        this.isUpload = false
        this.$message({
          message: '上传文件失败',
          type: 'error'
        })
      })
    },
    uploadDetail (res) { // 处理上传文件后的操作
      let apiUrl = ''
      if (res.filePostfix === '.csv') { // .csv 格式文件
        apiUrl = '/file/task/uploadFile/csv'
      } else { // .xls 或者 .xlxs格式文件
        apiUrl = '/file/task/uploadFile/excel'
      }
      uploadPost(apiUrl, res.fd).then((success) => {
        this.$message.closeAll()
        this.isUpload = false
        if (success.data.code === '200') {
          /* 将表格下单的数据存储至本地 */
          let saveData = success.data.data
          saveData.shopType = this.shopType
          saveData.filePostfix = res.filePostfix.substring(1)
          this.setTables(saveData)
          /***************************/
          this.uploadFileName = saveData.uploadFileName
          this.uploadStatus = 3
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          if (saveData.realNum === saveData.totalNum) { // 表格数据全部读取成功
            if (saveData.productNames.length > 8) {
              this.$alert('请尽量控制sku在8个之内', '提示', {
                confirmButtonText: '确定'
                // callback: action => {
                //   this.$message({
                //     type: 'info',
                //     message: `action: ${action}`
                //   })
                // }
              })
            } else {
              this.$router.push({ name: 'checkPackage', query: { tableType: 'tables' } })
            }
          } else { // 数据有未读取成功的
            this.errorTipObj.arr = []
          }
        } else if (success.data.code === '1001') {
          this.uploadStatus = 2
          this.$message({
            message: '数据参数读取失败, 请确认上传的文件与店铺类型是否一致',
            type: 'error'
          })
        } else {
          this.uploadStatus = 2
          this.$message({
            message: success.data.message,
            type: 'error'
          })
        }
      }).catch((err) => {
        this.$message.closeAll()
        this.isUpload = false
        console.error(err)
        this.$message({
          message: '上传文件失败',
          type: 'error'
        })
      })
    },
    ...mapActions([
      'setTables'
    ])
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../../assets/stylus/index.styl'
.tableBase
  text-align center
  .warning
    text-align left
    .tipsErr
      color $mainColor
      font-size $fontSize-l
      // font-weight bold
    p
      fontSize($fontSize-m, 1, $fontSize)
      margin-bottom 12px
      i
        margin-right 12px
        font-size 20px
      a
        text-decoration none
  .upload
    margin-top 60px
  .tips
    fontSize($fontSize, 1, $fontColor)
    margin-top 20px
  .failDetail
    display flex
    margin-top 24px
    justify-content center
    p
      fontSize($fontSize, 28px, #ffffff)
      padding 0 10px
      border-radius 14px
      margin-right 24px
      background $fontColor-o
      strong
        font-size 16px
        font-weight bold
    b
      align-self center
  .elAlert
    text-align left
    .errorTip
      padding 40px
      p
        fontSize($fontSize-l, 1, $fontColor)
        margin-bottom 12px
      .errorList
        border 1px solid #EBEEF5
        padding 12px 20px
        max-height 200px
        min-height 100px
        overflow auto
        margin-bottom 40px
        li
          margin-bottom 12px
          fontSize($fontSize-l, 1, $fontColor-o)
      .footer
        b
          margin 0 10px
    ::-webkit-scrollbar
      width 4px
      display block
    ::-webkit-scrollbar-thumb
      border-radius 2px
      background RGBA(136, 136, 136, 0.4)
      &:hover
        background RGBA(136, 136, 136, 1)
</style>
